package com.wyy.mall.tiny.service.impl;

import com.wyy.mall.tiny.common.api.CommonResult;
import com.wyy.mall.tiny.service.RedisService;
import com.wyy.mall.tiny.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * 会员管理Service实现类
 * created by 伍猷煜 on 2021/5/11 10:49 星期二
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {

    @Autowired
    private RedisService mRedisService;

    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;

    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    /**
     * 生成验证码
     *
     * @param telephone
     * @return
     */
    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0 ; i < 6 ; i++) {
            sb.append(new Random().nextInt(10));
        }
        mRedisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        mRedisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
        return CommonResult.success(sb.toString(), "获取验证码成功");
    }

    /**
     * 验证验证码和手机号码是否匹配
     *
     * @param telephone
     * @param authCode
     * @return
     */
    @Override
    public CommonResult verifyAuthCode(String telephone, String authCode) {
        if (!StringUtils.hasText(authCode)) { // 这种前端可以过滤掉，但是安全起见，有些东西前后端都需要做过滤
            return CommonResult.failed("请输入验证码");
        }
        String value = mRedisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        if (authCode.equals(value)) return CommonResult.success(null,"验证码校验成功");
        else return CommonResult.failed("验证码校验失败");
    }
}
